package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.ImportExcel;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.model.Maintainer;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.MaintainerService;
import com.gable.exhibition.util.CheckImportExcelMaintainer;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.ImportExcelMaintainerModel;
import com.gable.exhibition.view.ImportExcelView;
import com.gable.exhibition.view.MaintainerView;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Lesson on 2018/1/4.
 */
@Controller
@RequestMapping(value="/maintainer")
public class MaintainerController {

        Logger logger  = Logger.getLogger(this.getClass());

        @Autowired
        MaintainerService maintainerService;

        @Autowired
        CheckImportExcelMaintainer checkImportExcelMaintainer;

        @RequestMapping(value="/page")
        public String page (HttpServletRequest request, HttpServletResponse response){
            return "maintainer/maintainer-page";
        }


        @RequestMapping(value="/queryMaintainerList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryMaintainerList(HttpServletRequest request, HttpServletResponse response, MaintainerView maintainerView){
            try{
                ReturnResultUtil rru = maintainerService.queryMaintainerList(maintainerView);
                logger.info(JSON.toJSONString(rru));
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        }


        @RequestMapping(value="/addOrUpdateMaintainer",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil addOrUpdateMaintainer(HttpServletRequest request, HttpServletResponse response, MaintainerView maintainerView){
            try{
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                User user = CacheData.getSessionUser(null,1);
                if(maintainerView.getMaintainerId() != null){
                    maintainerView.setCreateTime(df.format(new Date()));
                    maintainerView.setCreatePerson(user.getUserId());
                }else{
                    maintainerView.setUpdateTime(df.format(new Date()));
                    maintainerView.setUpdatePerson(user.getUserId());
                }
                return maintainerService.addOrUpdateMaintainer(maintainerView);
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500, MessageUtil.SAVEEXCEPTION);
        }


        @RequestMapping(value="/queryMaintainerInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryMaintainerIdInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam("maintainerId") Long maintainerId){
            try{
                ReturnResultUtil rru = maintainerService.queryMaintainerInfo(maintainerId);
                logger.info(JSON.toJSONString(rru));
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        }

        @RequestMapping(value="/import")
        public String importManufacturer(HttpServletRequest request, HttpServletResponse response){
            return "maintainer/maintainer-import";
        }

        @RequestMapping(value="/maintainerExcel",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil maintainerExcel(HttpServletRequest request, HttpServletResponse response){

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
            try {
                Long ym = new Date().getTime();
                String filePath = "upload/" + ym;
                if (files != null && files.size() > 0) {
                    for (MultipartFile m : files) {
                        if (m.getBytes().length == 0) {
                            return new ReturnResultUtil(500, MessageUtil.PLEASEUPLOADFILE);
                        }
                        String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                        if (!suffix.equals("xlsx")) {
                            return new ReturnResultUtil(500, MessageUtil.FILEFORMATWRONG);
                        }
                        filePath = filePath + suffix;
                        File file = new File(rootPath + filePath);
                        if (file.exists()) {
                            file.delete();
                            file.mkdirs();
                        } else {
                            file.mkdirs();
                        }
                        m.transferTo(file);
                    }
                    User user = CacheData.getSessionUser(null,1);
                    List<Object> list = ImportExcel.excelRead(rootPath + filePath, CheckImportExcelMaintainer.properties, ImportExcelMaintainerModel.class);
                    CheckImportExcelMaintainer.resultMap.put(user.getUserId(), list);
                    logger.info("==================" + JSON.toJSONString(list));
                    return new ReturnResultUtil(200, MessageUtil.UPLOADSUCCESS, list);

                } else {
                    return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return  new ReturnResultUtil(500,MessageUtil.UPLOADEXCEPTION);
        }

    @RequestMapping(value="/checkExcelMaintainer",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkExcelMaintainer(HttpServletRequest request, HttpServletResponse response){

        ImportExcelView importExcelView = new ImportExcelView();
        try {
            User user = CacheData.getSessionUser(null,1);
            List<ImportExcelMaintainerModel> list =(List<ImportExcelMaintainerModel>)CheckImportExcelMaintainer.resultMap.get(user.getUserId());
            importExcelView = checkImportExcelMaintainer.checkMaintainer(list);
            return new ReturnResultUtil(200,MessageUtil.EXAMINESUCCESS,importExcelView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.EXAMINEERROR);
    }


    @RequestMapping(value="/saveMaintainerByExecl",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveMaintainerByExecl(HttpServletRequest request, HttpServletResponse response){
        try {
            User user = CacheData.getSessionUser(null, 1);
            List<ImportExcelMaintainerModel> list = (List<ImportExcelMaintainerModel>) CheckImportExcelMaintainer.resultMap.get(user.getUserId());
            ReturnResultUtil rru = maintainerService.saveMaintainerByExcel(list,user);
            CheckImportExcelMaintainer.resultMap.remove(user.getUserId());
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }


    @RequestMapping(value="/queryMaintainerListByManuId",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public  ReturnResultUtil queryMaintainerListByManuId(HttpServletRequest request, HttpServletResponse response){
        try {
            if(StringUtil.isEmpty(request.getParameter("manufacturerId"))){
                return new ReturnResultUtil(500,MessageUtil.MANUFACTURERIDISNULL);
            }
            Long manufacturerId = Long.parseLong(request.getParameter("manufacturerId"));
            ReturnResultUtil rru = maintainerService.queryMaintainerListByManuId(manufacturerId);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }


    @RequestMapping(value="/addMaintainerByManuId",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public  ReturnResultUtil addMaintainerByManuId(HttpServletRequest request, HttpServletResponse response,MaintainerView maintainerView){
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long userId = null;
            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }
            User user =CacheData.getSessionUser(userId,1);
            if(maintainerView.getManufacturerId() == null){
                return new ReturnResultUtil(500,MessageUtil.MANUFACTURERIDISNULL);
            }
            if(StringUtil.isEmpty(maintainerView.getMaintainerNo())){
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERNOISNULL);
            }
            if(StringUtil.isEmpty(maintainerView.getMaintainerName())){
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERNAMEISNULL);
            }

            if(StringUtil.isEmpty(maintainerView.getMaintainerContacts())){
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERCONTACTSISNULL);
            }

            if(StringUtil.isEmpty(maintainerView.getMaintainerPhone())){
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERPHONEISNULL);
            }

            maintainerView.setCreatePerson(user.getUserId());
            maintainerView.setCreateTime(df.format(new Date()));
            ReturnResultUtil rru = maintainerService.addMaintainerByManuId(maintainerView);
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }


    @RequestMapping(value="/detainMaintainerByManuId",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public  ReturnResultUtil detainMaintainerByManuId(HttpServletRequest request, HttpServletResponse response){
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long userId = null;
            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }
            User user =CacheData.getSessionUser(userId,1);
            if(StringUtil.isEmpty(request.getParameter("maintainerId"))){
                return new ReturnResultUtil(500,MessageUtil.MAINTAINERIDISNULL);
            }
            Long maintainerId = Long.parseLong(request.getParameter("maintainerId"));
            Integer isDel = Integer.parseInt(request.getParameter("isDel"));
            Maintainer maintainer= new Maintainer();
            maintainer.setMaintainerId(maintainerId);
            maintainer.setUpdatePerson(user.getUserId());
            maintainer.setUpdateTime(df.format(new Date()));
            maintainer.setIsDel(isDel);
            ReturnResultUtil rru = maintainerService.detainMaintainerByManuId(maintainer);
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

    /**
     * 根据维修商名称获取维修商基本信息
     * @param request
     * @param maintainerView
     * @return
     */
    @RequestMapping(value="/queryMaintainerByName",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryMaintainerByName(HttpServletRequest request,MaintainerView maintainerView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS);
        try {
            String manufacturerName = maintainerView.getManufacturerName();
            if(!StringUtils.isEmpty(manufacturerName)){
                resultUtil = maintainerService.queryMaintainerByName(maintainerView);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

}
